package com.hopechart.micro.common.generator.controller;

import com.hopechart.micro.common.exception.BusinessException;
import com.hopechart.micro.common.exception.ErrorCode;
import com.hopechart.micro.common.generator.AbstractGenerator;
import com.hopechart.micro.util.StringUtil;
import freemarker.template.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileWriter;
import java.util.Map;

/**
 * @author daijiang@hopechart.com
 */
public class ControllerGenerator extends AbstractGenerator {

    private static final Logger logger = LoggerFactory.getLogger(ControllerGenerator.class);

    @Override
    public void executor(String tableName, String modelName) {

        Configuration cfg = getFreemarkerConfiguration();
        Map<String, Object> data = getTemplateParam(tableName, modelName);
        // USER_NAME to UserName
        String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);

        if(!StringUtil.isEmpty(modelName)) {
            modelNameUpperCamel = modelName;
        }
        try {
            File controllerFile = new File(getControllerSavePath() + modelNameUpperCamel + "Controller.java");
            if (!controllerFile.getParentFile().exists()) {
                controllerFile.getParentFile().mkdirs();
            }
            cfg.getTemplate("controller.ftl").process(data, new FileWriter(controllerFile));
            logger.info(modelNameUpperCamel + "Controller.java 生成成功.");
        } catch (Exception e) {
            logger.error("控制层代码生成异常，{}", e.getMessage(), e);
            throw new BusinessException(ErrorCode.GEN_CONTROL, "控制层代码生成异常，{" + e.getMessage() + "}", e);
        }
    }
}
